package xyc.szk.web.servlet.session;
/*
 * @Description:
 * @Author: 山志凯
 * @Date: 2021-04-14
 * @Time: 09:19
 */

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //登录验证
        //1、获取请求参数
        String userName = req.getParameter("userName");
        String userPwd = req.getParameter("userPwd");
        String checkCode = req.getParameter("checkCode");//获取用户输入的验证码
        HttpSession session = req.getSession();
        //验证验证码
        if (checkCode!=null && checkCode.length()!=0) {
            //验证码非空，获取服务器保存的验证码

            String code = (String) session.getAttribute("code");
            if (code!=null&&code.equals(checkCode)) {
                //验证码通过，验证用户名和密码
                if (userName.equals("admin")&&userPwd.equals("123")) {
                    //用户名和密码验证通过
                    //1、将用户的登录信息保存到域session对象中
                    session.setAttribute("loginInfo",userName);
                    //请求转发到一个servlet：/success
                    req.setAttribute("msg","，欢迎回来！");//向请求域中存储一个key-value对
                    req.getRequestDispatcher("/success").forward(req,resp);
                } else {
                    //用户名或密码错误，请求转发到一个servlet：/fail
                    req.setAttribute("msg","用户名或密码错误！");//向请求域中存储一个key-value对
                    req.getRequestDispatcher("/fail").forward(req,resp);
                }
            } else {
                //验证码未通过，请求转发到一个servlet：/fail
                req.setAttribute("msg","验证码错误！");//向请求域中存储一个key-value对
                req.getRequestDispatcher("/fail").forward(req,resp);
            }
        }
        //登陆成功后让本次的验证码失效
       // session.invalidate();
        session.removeAttribute("code");//session中的验证码失效
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
